package org.mespilus.mespilusweb.ui.usermanagement.client.presenter;

import java.util.List;

import org.mespilus.mespilusweb.ui.usermanagement.client.UserListPanel;
import org.mespilus.mespilusweb.ui.usermanagement.client.events.UserListChangedEvent;
import org.mespilus.mespilusweb.ui.usermanagement.client.events.UserListChangedHandler;
import org.mespilus.mespilusweb.ui.usermanagement.client.events.UserListGetEvent;
import org.mespilus.mespilusweb.ui.usermanagement.client.events.MemberListSearchEvent;
import org.mespilus.mespilusweb.ui.usermanagement.client.events.UserManagementBus;
import org.mespilus.mespilusweb.ui.usermanagement.client.model.UsefulMember;

public class UserListPresenter implements UserListChangedHandler {
	UserListPanel userListPanel;

	public UserListPresenter() {
		UserManagementBus.getInstance().registerToUserListChange(this);
	}

	public UserListPanel getUserListPanel() {
		return userListPanel;
	}


	public void setUserListPanel(UserListPanel userListPanel) {
		this.userListPanel = userListPanel;
	}

	private Object[][] listToObjectArray(List<UsefulMember> persons) {
		Object[][] data = new Object[persons.size()][2];
		for (int i = 0; i < persons.size(); i++) {
			data[i][0] = persons.get(i).getMail();
			data[i][1] = persons.get(i).getName();
		}
		return data;
	}

	@Override
	public void processUserListChanged(UserListChangedEvent event) {
		userListPanel.showResult(listToObjectArray(event.getMembers()));
	}

	public void getAsyncUserList() {
		UserListGetEvent event = new UserListGetEvent();
		UserManagementBus.getInstance().fireUserListGetEvent(event);
	}

	public void userSelected(String email) {
		MemberListSearchEvent event = new MemberListSearchEvent();
		event.setMail(email);
		UserManagementBus.getInstance().fireUserListSearchdEvent(event);
	}

}
